package com.gopay.common.cipher.utils;

/**
 * 更换密钥时候的锁机制
 * Created by zyt on 2017/4/18.
 */
public class KeyLockUtils {
    //锁
    private static Boolean lock = false;
    //锁定的时候最大重试次数
    private static final int RETRYTIMES_WHILE_LOCK = 5;
    //锁的时候，每次尝试后等待的时间，单位ms
    private static final int MILLISECOND_WAIT_PER_TIME = 10;

    /**
     * 加锁
     */
    public static void lock(){
        lock = true;
    }

    /**
     * 解锁
     */
    public static void unLock(){
        lock = false;
    }

    /**
     * 是否加锁
     * @return
     */
    public static Boolean isLock(){
        return lock;
    }

    /**
     * 尝试去获取锁
     * @return
     */
    public static Boolean getLock(){
        for(int i = 0; i < RETRYTIMES_WHILE_LOCK; i++){
            if(!isLock()){
                return true;
            }
            try {
                Thread.sleep(MILLISECOND_WAIT_PER_TIME);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return false;
    }
}
